package cn.tedu.jdbc;

import cn.tedu.jdbc.utils.DbUtils;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 使用preparedStatement将表中的图片查询出来（读取到本地）
 */
public class JDBCTest18 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DbUtils.getConnection();
            String sql = "select img from t_img where name = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,"640.jpg");
            rs = ps.executeQuery();
            if(rs.next()){
                InputStream in = rs.getBinaryStream("img");
                OutputStream out = new FileOutputStream("D:\\640.jpg");
                byte[] bytes = new byte[1024];
                int readCount = 0;
                while ((readCount = in.read(bytes)) != -1) {
                    out.write(bytes,0,readCount);
                }
                out.flush();
                in.close();
                out.close();
            }
        } catch (SQLException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtils.close(conn,ps,rs);
        }
    }
}
